import React, { lazy, Suspense } from "react";
import { Routes, Route, Navigate } from "react-router-dom";
import Layout from "@/components/Layout";
import Login from "@/pages/Login";
import Register from "@/pages/Register";
import { AuthProvider, useAuth } from '@/contexts/authContext.tsx';
import { Empty } from '@/components/Empty';
import { SystemProvider } from '@/contexts/SystemContext';
import { AudioProvider } from '@/contexts/AudioContext';
import { MessageProvider } from '@/contexts/MessageContext';
import { menuData } from "@/data/menuData";
import { extractRoutesFromMenus, getComponentNameByPath } from "@/lib/utils";

// 受保护的路由组件
const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
  const { isAuthenticated } = useAuth();
  
  if (!isAuthenticated) {
    return <Navigate to="/login" replace />;
  }
  
  return <Layout>{children}</Layout>;
};

// 公开路由组件（不需要认证）
const PublicRoute = ({ children }: { children: React.ReactNode }) => {
  const { isAuthenticated } = useAuth();
  
  if (isAuthenticated) {
    return <Navigate to="/" replace />;
  }
  
  return children;
};

// 获取默认路由路径
const getDefaultRoute = () => {
  // 从菜单数据中查找第一个启用的菜单项作为默认路由
  const routes = extractRoutesFromMenus(menuData);
  const defaultRoute = routes.find(route => route.path === '/') || routes[0];
  return defaultRoute?.path || '/workbench';
};

// 从菜单数据中提取所有唯一的组件名称
const extractComponentNames = (menuData: any[]): Set<string> => {
  const componentNames = new Set<string>();
  
  const traverseMenus = (menus: any[]) => {
    menus.forEach(menu => {
      if (menu.status === 1 && menu.path && menu.componentName && menu.type === 1) {
        componentNames.add(menu.componentName);
      }
      
      if (menu.children && menu.children.length > 0) {
        traverseMenus(menu.children);
      }
    });
  };
  
  traverseMenus(menuData);
  return componentNames;
};

// 生成基于菜单数据的组件映射
const generatePageComponents = () => {
  const components: Record<string, React.LazyExoticComponent<any>> = {};
  const componentNames = extractComponentNames(menuData);
  
  // 为每个组件名称创建懒加载导入
  componentNames.forEach(componentName => {
    switch (componentName) {
      case 'Home':
        components.Home = lazy(() => import("@/pages/Home"));
        break;
      case 'Workbench':
        components.Workbench = lazy(() => import("@/pages/Workbench"));
        break;
      case 'Products':
        components.Products = lazy(() => import("@/pages/Products"));
        break;
      case 'Projects':
        components.Projects = lazy(() => import("@/pages/Projects"));
        break;
      case 'Requirements':
        components.Requirements = lazy(() => import("@/pages/Requirements"));
        break;
      case 'Tasks':
        components.Tasks = lazy(() => import("@/pages/Tasks"));
        break;
      case 'Bugs':
        components.Bugs = lazy(() => import("@/pages/Bugs"));
        break;
      case 'Knowledge':
        components.Knowledge = lazy(() => import("@/pages/Knowledge"));
        break;
      case 'Kpi':
        components.Kpi = lazy(() => import("@/pages/Kpi"));
        break;
      case 'Assessment':
        components.Assessment = lazy(() => import("@/pages/Assessment"));
        break;
      case 'Feedback':
        components.Feedback = lazy(() => import("@/pages/Feedback"));
        break;
      case 'Reports':
        components.Reports = lazy(() => import("@/pages/Reports"));
        break;
      case 'Users':
        components.Users = lazy(() => import("@/pages/Users"));
        break;
      case 'Roles':
        components.Roles = lazy(() => import("@/pages/Roles"));
        break;
      case 'Menus':
        components.Menus = lazy(() => import("@/pages/Menus"));
        break;
      case 'Messages':
        components.Messages = lazy(() => import("@/pages/Messages"));
        break;
      case 'Help':
        components.Help = lazy(() => import("@/pages/Help"));
        break;
      case 'Terms':
        components.Terms = lazy(() => import("@/pages/Terms"));
        break;
      case 'Privacy':
        components.Privacy = lazy(() => import("@/pages/Privacy"));
        break;
      case 'Settings':
        components.Settings = lazy(() => import("@/pages/Settings"));
        break;
      case 'ToastDemo':
        components.ToastDemo = lazy(() => import("@/pages/ToastDemo"));
        break;
      default:
        console.warn(`未找到组件 ${componentName} 的导入配置`);
    }
  });
  
  return components;
};

// 动态生成页面组件映射
const pageComponents = generatePageComponents();

export default function App() {
  // 动态生成受保护的路由配置
  const generateProtectedRoutes = () => {
    const routes = extractRoutesFromMenus(menuData);
    
    // 调试：输出所有路由信息
    console.log('提取的路由配置:', routes);
    
    return routes.map(route => {
      const componentName = getComponentNameByPath(route.path);
      
      // 调试：输出每个路由的组件名称
      console.log(`路由路径: ${route.path}, 组件名称: ${componentName}`);
      
      // 从预定义的组件映射中获取组件
      const LazyComponent = pageComponents[componentName] || lazy(() => Promise.resolve({ default: Empty }));
      
      return (
        <Route 
          key={route.path} 
          path={route.path} 
          element={
            <ProtectedRoute>
              <Suspense fallback={
                <div className="h-screen flex items-center justify-center">
                  <div className="text-center">
                    <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
                    <p className="text-gray-600">页面加载中...</p>
                  </div>
                </div>
              }>
                <LazyComponent />
              </Suspense>
            </ProtectedRoute>
          } 
        />
      );
    });
  };

  return (
    <AuthProvider>
      <SystemProvider>
        <AudioProvider>
          <MessageProvider>
            <Routes>
              {/* 公开路由 - 登录页面 */}
              <Route 
                path="/login" 
                element={
                  <PublicRoute>
                    <Login />
                  </PublicRoute>
                } 
              />
              
              {/* 公开路由 - 注册页面 */}
              <Route 
                path="/register" 
                element={
                  <PublicRoute>
                    <Suspense fallback={
                      <div className="h-screen flex items-center justify-center">
                        <div className="text-center">
                          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
                          <p className="text-gray-600">页面加载中...</p>
                        </div>
                      </div>
                    }>
                      <Register />
                    </Suspense>
                  </PublicRoute>
                } 
              />
              
              {/* 受保护的路由 */}
              {generateProtectedRoutes()}
              
              {/* 默认重定向到菜单数据中的第一个可用路由 */}
              <Route path="/" element={<Navigate to={getDefaultRoute()} replace />} />
              
              {/* 404 页面 */}
              <Route path="*" element={
                <ProtectedRoute>
                  <div className="h-screen flex items-center justify-center">
                    <div className="text-center">
                      <h1 className="text-4xl font-bold text-gray-800 mb-4">404</h1>
                      <p className="text-gray-600 mb-8">页面未找到</p>
                      <button 
                        className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                        onClick={() => window.history.back()}
                      >
                        返回上一页
                      </button>
                    </div>
                  </div>
                </ProtectedRoute>
              } />
            </Routes>
          </MessageProvider>
        </AudioProvider>
      </SystemProvider>
    </AuthProvider>
  );
}